import { CartItem } from "@/types/cart";
import { IApiRes } from "@/types/data";

import request from "@/utils/request";
import { defineStore } from "pinia";
import useStore from "..";

const useCartStore = defineStore('cart', {
  // 状态
  state() {
    return {
      list: [] as CartItem[] // 购物车数组
    }
  },
  persist: {
    enabled: true,
    strategies: [{key:'rabbit-cart-76'}]
    // key: 'category'
  },
  // 计算
  getters: {
    isLogin(): boolean{ 
      const { user } = useStore()
      return Boolean(user.profile.token)
    },
    // 是否全部选中
    isAllSelected(): boolean {
      return this.effectiveList.every(item => item.selected)
    },
    // 计算有效的商品
    effectiveList() : CartItem[]{
      return this.list.filter((it: CartItem) => it.isEffective)
    },
    // 商品的数量
    effectiveListCounts() : number{
      return this.effectiveList.reduce((acc: number, cur: CartItem)=>{
        return acc + cur.count
      }, 0)
    },
    // 商品的总价格
    effectiveListPrice() : number{
      return this.effectiveList.reduce((acc: number, cur: CartItem) => {
        return acc + Number(cur.price) * cur.count
      }, 0)
    },
    selectedList(): CartItem[] {
      return this.effectiveList.filter(it => it.selected)
    },
    selectedNum(): number {
      return this.selectedList.reduce((acc, cur)=>{
        return acc + cur.count
      }, 0)
    },
    selectedListPrice(): number {
      return this.selectedList.reduce((acc, cur)=>{
        return acc + cur.count * +cur.price
      }, 0)
    },
  },
  // 方法
  actions: {
     // 合并购物车
   async mergeLocalCart() {
     const data = this.list.map(({ skuId, selected, count }) => ({
       skuId,
       selected,
       count
     }))
     await request.post('/member/cart/merge', data)
     // 合并成功，重新获取购物车列表
     this.getCartList()
   },
    // 修改全选或者全不选
    async updateCartAllSelected(isSelected: boolean) {
      if(this.isLogin){
        await request.put('/member/cart/selected', {
          selected: isSelected,
        })
        // 获取购物车列表
        this.getCartList()
      } else {
        // 没有登录的情况下
        this.effectiveList.forEach(it => it.selected = isSelected)
      }
    },
    // 修改购物车商品: 修改选中状态 + 数量
    async updateCart(
      skuId: string,
      data: { selected?: boolean; count?: number }
    ) {
      if(this.isLogin){
        await request.put(`/member/cart/${skuId}`, data)
        // 重新获取最新购物车列表
        this.getCartList()
      } else {
        // 本地修改，找到这商品，修改对应的属性
        const g = this.effectiveList.find(it => it.skuId === skuId)
        if(!g){return}
        // 如果当前改的是 是否选中
        if(data.selected !== undefined){
          g.selected = data.selected
        }
        if(data.count !== undefined) {
          g.count = data.count
        }
      }
    },
    // 删除购物车商品
    async delCart(skuIds: string[]) {
      if(this.isLogin){
        await request.delete('/member/cart', {
          data: { ids: skuIds }
        })
        // 重新获取最新购物车列表
        this.getCartList()
      } else {
        // 要删除的skuIds: ['300289261', 'abcdafdadsfds', 'a']
        // 要留下来的条件是：list中的商品的skuId 不在 数组skuIds中
        this.list = this.list.filter(it => {
          return skuIds.includes(it.skuId) === false
        })
      }
    },
// 获取购物车列表
    async getCartList() {
  if (this.isLogin) {
    const res = await request.get<IApiRes<CartItem[]>>('/member/cart')
    this.list = res.data.result
  } else {
    // 遍历发送请求, 校验更新sku商品的库存和价格, 是否有效
    this.list.forEach(async (cartItem) => {
      const { skuId } = cartItem
      // 根据 skuId 获取最新商品信息
      const res = await request.get<IApiRes<CartItem>>(
        `/goods/stock/${skuId}`
      )
      // 保存最新商品信息
      const lastCartInfo = res.data.result
      // 更新商品现价
      cartItem.nowPrice = lastCartInfo.nowPrice
      // 更新商品库存
      cartItem.stock = lastCartInfo.stock
      // 更新商品是否有效
      cartItem.isEffective = lastCartInfo.isEffective
       })
      }
    },
  },
});

export default useCartStore